package com.application.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class ConfigUtil{

	private static ConcurrentMap<String,ConcurrentMap<String,String>> configFileMap = new ConcurrentHashMap<String,ConcurrentMap<String,String>>();
	private static Map<String,Properties> loaderMap	= new HashMap<String,Properties>();
    private static final String DEFAULT_CONFIG_FILE = "/application.properties" ;
	
	private static Properties prop = null;
    public static Properties getPropFromFS(String fileName) throws IOException  {
		Properties prop = loaderMap.get(fileName);
		if (prop != null) {
			return prop ;
        }
        prop = new Properties();
        InputStream in;
        in = ConfigUtil.class.getResourceAsStream(fileName);
        prop.load(in);
        loaderMap.put(fileName, prop);	 	
		return prop;     
    }
	public static String getStringByKey(String key,String propName) {
		try {			
			prop = getPropFromFS(propName);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		key = key.trim();
        ConcurrentMap<String,String> configMap;
		if (!configFileMap.containsKey(propName)) {
            configMap =new ConcurrentHashMap<String,String>();
			configFileMap.put(propName,configMap);
		}        
        configMap = configFileMap.get(propName);
		if (!configMap.containsKey(key)) {
			if(prop.getProperty(key)!=null){
				configMap.put(key, prop.getProperty(key));
			}
		}
		return configMap.get(key);
	}
	public static String getStringByKey(String key) {
        return getStringByKey(key,DEFAULT_CONFIG_FILE);
	}
	public static Properties getProperties()
	{
		try {
			return getPropFromFS(DEFAULT_CONFIG_FILE);
		} catch (Exception e) {
			return null;
		}
	}
	
	

}